package main

import (
	"app/newws/ws"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/olahol/melody"
)

func main() {
	r := gin.Default()
	m := melody.New() //ws包
	m.Upgrader.CheckOrigin = func(r *http.Request) bool { return true }

	// WS 路由
	r.GET("/ws", func(c *gin.Context) {
		_ = m.HandleRequest(c.Writer, c.Request)
	})
	// WS 路由
	r.GET("/setFoom", func(c *gin.Context) {
		roomId := c.Query("roomId")
		content := c.Query("content")
		ws.SendToRoom(m, roomId, content)
		fmt.Println("setFoom 发送成功")
	})
	r.GET("/setUser", func(c *gin.Context) {
		userId := c.Query("userId")
		content := c.Query("content")
		err := ws.SendToUser(userId, content)
		fmt.Println("setUser 发送成功", err)
	})

	// 注册回调
	m.HandleConnect(ws.HandleConnect)
	m.HandleMessage(func(s *melody.Session, msg []byte) {
		ws.HandleMessage(s, msg, m)
	})
	m.HandleDisconnect(ws.HandleDisconnect)

	r.Run(":8080")
}
